import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { setToken, removeToken } from '@/utils/auth'
import { fetchUserInfo } from '@/api/users'

const initialState = {
    name: '',
    role: [],
    token: ''
}

export const getUserInfo = createAsyncThunk('user/fetchUserInfo', async () => {
    const response = await fetchUserInfo()
    return response.data
})


const usersSlice = createSlice({
    name: 'user',
    initialState,
    reducers: {
        userUpdate( state, action ) {
            console.log('action', action)
        },
        userSetToken( state, action ) {
            
            state.token = action.payload.token
            
            setToken(action.payload.token)
        },
        userRemoveInfo( state ) {
            state.name = ''
            state.role = []
            state.token = ''

            removeToken()
        }
        
    },
    extraReducers( builder ) {
        builder.addCase(getUserInfo.fulfilled, (state, action) => {
            state.name = action.payload.name
            state.role = action.payload.role
          })
    }
})

export const  { userUpdate, userSetToken, userRemoveInfo } = usersSlice.actions

export default usersSlice.reducer